package com.macllvm.whale.model;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Observable;
import com.macllvm.whale.entity.Message;
import android.util.Log;


public class MessageManager extends Observable {
    private static final String TAG = "MessageManager";
    private ConcurrentHashMap<String, LinkedList<Message>> msgMap = new ConcurrentHashMap<String, LinkedList<Message>>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void add(String ip, Message m){
        LinkedList<Message>  list = msgMap.get(ip);

        Lock l = lock.writeLock();
        l.lock();
        try{
           if(null == list) {
               list = new LinkedList<Message>();
               msgMap.put(ip, list);
           }
           list.add(m);
           this.setChanged();
           this.notifyObservers(ip);
        } finally {
           l.unlock();
        }

              
    }

    public List<Message> getDataSource(String ip) {
        LinkedList<Message>  list = msgMap.get(ip);
        if(null == list) {
            Lock l = lock.writeLock();
            l.lock();
            try {
                list = new LinkedList<Message>();
                msgMap.put(ip, list);
            }finally {
                l.unlock();
            }
        }
        return list;
    }


}
